package org.sang;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.Map;

/**
 * Created by sang on 16-12-22.
 */
@RestController
public class WsController {
    @Autowired
    private SimpMessagingTemplate template;

    //推送消息的第一种方式
    //@Header获取请求头 @Headers包含请求头以及一些额外的消息
    //headers.get("nativeHeaders").get("token").get(0)也可以获取请求头消息，其中headers.get("nativeHeaders").get("token")是LinkedList
    @MessageMapping("/welcome")
    @SendTo("/topic/getResponse")
    public ResponseMessage say(RequestMessage message, @Header("token") String token,
                               @Headers Map<String, Object> headers) {
        System.out.println(message.getName());
        System.out.println(token);
        System.out.println(headers.get("nativeHeaders"));
        Map<String, LinkedList> nativeHeaders = (Map<String, LinkedList>) headers.get("nativeHeaders");
        System.out.println(nativeHeaders.get("token").get(0));
        System.out.println(nativeHeaders.get("token1").get(0));
//        Set<Map.Entry<String, Object>> entries = headers.entrySet();
//        for (Map.Entry<String, Object> entry : entries) {
//            System.out.println(entry.getKey() + ":" + entry.getValue());
//        }
        return new ResponseMessage("welcome," + message.getName() + " !");
    }

    //推送消息的第二种方式，使用SimpMessagingTemplate发送消息
    @GetMapping("/hello")
//    @MessageMapping("/hello")
    public void send(String name, @Header("token") String topic,
                     @Headers Map<String, Object> headers) {

        System.out.println("name==" + name);
        System.out.println("topic==" + topic);
        System.out.println("headers==" + headers);
        //第一个参数：订阅的地址  第二个参数：发送的消息
        template.convertAndSend("/topic/getResponse", name);
        //发送消息给特定用户，前端需要动态获取当前登陆用户的用户名，生成客户端订阅地址
//        template.convertAndSend("/topic/"+name, "内容");
    }
}
